package com.java1412.controller;

import com.java1412.utils.AliyunOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author java1412
 * @create 2021-07-20 14:10
 */
@Controller
public class OssController {
    @Autowired
    private AliyunOssUtil ossUtil;

    @GetMapping("/")
    public String showUploadFile() {
        return "upload";
    }

    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (null != file) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    // 把file里的内容复制到newFile中
                    file.transferTo(newFile);
                    String upload = ossUtil.upload(newFile);
                    // 图片回显地址
                    System.out.println("path = " + upload);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
